package io.dirac.controller;

import io.dirac.dto.OrderSettlementDto;
import io.dirac.entity.OrderDetail;
import io.dirac.entity.OrderSurvey;
import io.dirac.result.Result;
import io.dirac.service.OrderDetailService;
import io.dirac.service.OrderSurveyService;
import io.dirac.service.ShoppingCartService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("order-settlement")
public class OrderSettlementController {

    @Autowired
    private OrderSurveyService orderSurveyService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping
    public Result settle(@RequestBody OrderSettlementDto orderSettlementDto) {
        OrderSurvey orderSurvey = orderSettlementDto.getOrderSurvey();
        List<OrderDetail> orderDetails = orderSettlementDto.getOrderDetails();
        List<Long> cartItemIds = orderSettlementDto.getCartItemIds();

        // save order survey
        orderSurveyService.save(orderSurvey);

        // save order details of this order
        Long orderId = orderSurvey.getId();
        for (OrderDetail orderDetail : orderDetails) {
            orderDetail.setOrderId(orderId);
        }
        orderDetailService.saveBatch(orderDetails);

        // delete corresponding items from shopping cart
        shoppingCartService.removeByIds(cartItemIds);

        return Result.success(orderSurvey.getId());
    }
}
